package com.process.demo;

import com.alibaba.fastjson.JSON;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * package com.process
 * description:
 *
 * @author tree
 * @date 2019-05-30 10:34
 */
public class ProcessShellDemo {
    static String bashPath = "/Users/xingyun/IdeaProjects/eclipselinkDemo/src/main/java/com/process/demo";
    static String outputPath = "/Users/xingyun/IdeaProjects/eclipselinkDemo/src/main/java/com/process/demo/process.out";
    static String errorPath = "/Users/xingyun/IdeaProjects/eclipselinkDemo/src/main/java/com/process/demo/error.out";

    public static void main(String[] args) throws IOException {
        System.err.println(JSON.toJSONString(System.getenv()));

        List<String> list = new ArrayList<>();
        list.add("sh");
        list.add("echo.sh");
        list.add("param1");
        list.add("param2");
        list.add("param3");
        File outputFile = new File(outputPath);
        if(!outputFile.exists()){
            outputFile.createNewFile();
        }
        File errorFile = new File(errorPath);
        if(!errorFile.exists()){
            errorFile.createNewFile();
        }

        ProcessBuilder processBuilder = new ProcessBuilder(list);
        processBuilder.redirectInput(outputFile);
        processBuilder.redirectError(errorFile);
        processBuilder.directory(new File(bashPath));
        processBuilder.redirectErrorStream(true);

        BufferedReader br = null;
        BufferedWriter bw = null;
        try {
            Process process = processBuilder.start();
            br = new BufferedReader(new InputStreamReader(process.getInputStream()));
            bw = new BufferedWriter(new FileWriter(outputFile));
            String line;
            while ((line = br.readLine()) != null) {
                System.out.println(line);
                bw.write(line);
                bw.write("\n");
                //写入文件中
//                System.err.println(process.exitValue());
            }
            bw.flush();
//            System.err.println(process.exitValue());
            int exitCode = process.waitFor();
            System.out.println("exitCode = "+exitCode);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            if(br != null) {
                br.close();
            }
        }


    }
}
